<?php
use Core\Paginator\Adapter\Collection as CollectionPaginator;

function commentList($nid, $pid, $limit = 10)
{
    $di = \Phalcon\Di::getDefault();
    $commentConfig = $di->getShared('config')->get('m.comment.config');
    $query = [
        'conditions' => [
            'nid' => $nid,
            'pid' => $pid
        ],
        'sort' => [
            'changed' => -1
        ],
        'limit' => $commentConfig['comment_number'],
        'skip' => 20
    ];
    $data = $di->getShared('entityManager')->get('comment', $query);
    $dataPagination = new CollectionPaginator([
        'data' => $data,
        'query' => $query,
        'page' => 1,
        'collection' => '\Modules\Comment\Entity\Comment'
    ]);
    return $dataPagination->getPaginate();
}

function comment(\Core\Mvc\Entity\Entity $node)
{
    $di = \Phalcon\Di::getDefault();
    $commentConfig = $di->getShared('config')->get('m.comment.config');
    $roles = $di->getShared('user')->getRoles();

    $nid = (string)$node->getId();
    $query = [
        'conditions' => [
            'nid' => $nid,
            'pid' => '0'
        ],
        'sort' => [
            'changed' => -1
        ],
        'limit' => $commentConfig['node_comment_number'],
        'skip' => 0
    ];
    $noComment = '还没有评论，快来抢占沙发吧～';

    if ($commentConfig['open_comment'] && array_intersect($commentConfig['open_comment'], $roles)) {
        $nodeField = $node->getField();
        $commentEntity = $di->getShared('entityManager')->get('comment');
        if (isset($nodeField['commentContentModel']) && is_string($nodeField['commentContentModel'])) {
            if (isset($nodeField['commentContentModel']) && $commentEntity instanceof \Core\Mvc\Entity\EntityInterface) {

                $field = $commentEntity->setContentModel($nodeField['commentContentModel'])->getField();
                $field['_action'] = $di->getShared('url')->get(['for' => 'commentSubmit'], ['nid' => $nid, 'pid' => 0]);
                $field['_form']['pid'] = 0;
                $field['_form']['id'] = 'main-comment-form';
                $commentForm = $commentEntity->setContentModel($nodeField['commentContentModel'])->setField($field)->addForm();
            } else {
                $commentForm = false;
            }
        } else {
            $commentForm = false;
        }
    } else {
        $noComment = '还没有评论，快登录后抢占沙发吧～';
        $commentForm = false;
    }

    $data = $di->getShared('entityManager')->find('comment', $query);

    $output = array(
        '#templates' => 'comment',
        '#module' => 'comment',
        'node' => $node,
        'noComment' => $noComment,
        'commentForm' => $commentForm ? $commentForm->renderForm('comment') : false,
        'data' => array(
            '#templates' => 'commentList',
            '#module' => 'comment',
            'data' => $data,
        ),
    );
    return $output;
}
